// import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:myapp/models/models.dart';
import 'package:myapp/repositories/repositories.dart';
// import 'package:meta/meta.dart';

part 'article_event.dart';
part 'article_state.dart';

class ArticleBloc extends Bloc<ArticleEvent, ArticleState> {
  final ArticleRepository articleRepository;

  ArticleBloc({
    required this.articleRepository
  }) : super(ArticleInitial()) {

    on<LoadArticleEvent>((event, emit) async {
      emit(ArticleLoading());
      try {
        var file= await articleRepository.getArticle(event.slug);
        emit(ArticleLoaded(article: file));
      } catch (e) {
        emit(ArticleError(error: e));
      }
    });

    on<CreateArticleEvent>((event, emit) async {
      await articleRepository.createArticle(event.article);
    });

    on<UpdateArticleEvent>((event, emit) async {
      await articleRepository.updateArticle(event.slug, event.article);
    });

    on<DeleteArticleEvent>((event, emit) async {
      await articleRepository.deleteArticle(event.slug);
    });

    on<ToggleFavoriteEvent>((event, emit) async {
      await articleRepository.createFavorite(event.slug);
    });



  }

  // @override
  // Future<void> close() {
  //   _articleSubscription.cancel();
  //   return super.close();
  // }
}
